package mul.Storage;

import java.util.List;

import mul.UI.HighScoreActivity;
import mul.UI.R;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.swarmconnect.SwarmLeaderboard;
import com.swarmconnect.SwarmLeaderboard.GotLeaderboardCB;
import com.swarmconnect.SwarmLeaderboard.GotScoresCB;
import com.swarmconnect.SwarmLeaderboardScore;
import mul.UI.*;




public class LeaderBoardInterface extends Thread{

        private final static int LEADERBOARD_ID = 291;
        private static SwarmLeaderboard lb;
        private static Context updateContext;
        private static SwarmLeaderboardScore[] leaderBoardArray = new SwarmLeaderboardScore[0];
        private static final int MAX_ENTERIES = 10;
        private static SwarmLeaderboardScore localUserScore;//is the local user
        private static HighScoreActivity listener;
        private static float tempScore;


        /**
         * Gets and Writes leaderboard and scores from server and/or local storage
         */
        public static void update(Context context){

                LeaderBoardInterface.updateContext = context;
                
                GotLeaderboardCB lbCallback = new GotLeaderboardCB() {

                        @Override
                        public void gotLeaderboard(SwarmLeaderboard leaderboard) {

                                if(leaderboard != null){
                                        lb = leaderboard;
                                        getLeaderBoardScores();

                                        Log.i("help", "GotLeaderBoard = Success!");
                                }else{
                                        Log.i("help", "Empty leaderboard!");
                                }
                        }
                };

                if(isNetworkAvailable(context)){
                        SwarmLeaderboard.getLeaderboardById(LEADERBOARD_ID, lbCallback);

                }else{
                        //OFFLINE
                        leaderBoardArray= readLeaderBoardFromLocal(updateContext);   
                        if(leaderBoardArray!=null){//hvis bruker==uregistrert -> tom skjerm vises
                        	if(HighScoreActivity.class.getSimpleName().equals(updateContext.getClass().getSimpleName())){
                                
                        		//updateHighscoreList was called
                        		leaderBoardArray = LocalPersistence.sortArray(leaderBoardArray);
                        		listener.updateGUI(leaderBoardArray);
                        	}
                        	else{
                        		// submitSCore was called
                        		localUserScore = readUserScoreFromLocal(updateContext);
                                Log.i("help", "WRITTEN :  "+localUserScore.user.username);
                                localUserScore.score = tempScore;
                                writesUserScoreToLocal(updateContext, localUserScore);

                                leaderBoardArray = LocalPersistence.addScoreToArray(localUserScore, leaderBoardArray, MAX_ENTERIES);
                                writesLeaderBoardToLocal(updateContext, leaderBoardArray);
                        	}
                        }

                }
        }


        private static void getLeaderBoardScores(){

                GotScoresCB callback = new GotScoresCB(){
                        @Override
                        public void gotScores(int pageNum, List<SwarmLeaderboardScore> scores) {
                                //Save POST to Local
                                leaderBoardArray = LocalPersistence.buildLeaderBoardArray(scores);
                                writesLeaderBoardToLocal(updateContext, leaderBoardArray);
                                Log.i("help", "GotBoardScoresBoard = Success!");


                                        // ONLINE
                                        if(HighScoreActivity.class.getSimpleName().equals(updateContext.getClass().getSimpleName())){
                                                //updateHighscoreList is called
                                                Log.i("help","ARRaysize:  "+leaderBoardArray.length);
                                                leaderBoardArray = LocalPersistence.sortArray(leaderBoardArray);
                                                listener.updateGUI(leaderBoardArray);
                                        }else{ 
                                        // submitSCore was called
                                        localUserScore = readUserScoreFromLocal(updateContext);
                                        localUserScore.score = tempScore;
                                        writesUserScoreToLocal(updateContext, localUserScore);

                                        leaderBoardArray = LocalPersistence.addScoreToArray(localUserScore,leaderBoardArray,MAX_ENTERIES);
                                        writesLeaderBoardToLocal(updateContext, leaderBoardArray);
                                        //To ONLINE
                                        lb.submitScore(tempScore);

                                }

                        }
                };

                if(lb != null){
                        lb.getTopScores(SwarmLeaderboard.LEADERBOARD_DATE_ALL_TIME,  callback);

                }else{

                }
        }



        public static void submitScore(Context context, float score){

                tempScore = score;
                update(context);

        }


        public static void updateHighScoreActivityList(HighScoreActivity context){

                update(context);

        }



        public synchronized static void writesUserScoreToLocal(Context context, SwarmLeaderboardScore object){
                String path = context.getString(R.string.LocalUserPath);
                LocalPersistence.witeObjectToFile(context, object, path);               

        }
        public synchronized static SwarmLeaderboardScore readUserScoreFromLocal(Context context){
                String path = context.getString(R.string.LocalUserPath);
                Object object = LocalPersistence.readObjectFromFile(context,path);


                SwarmLeaderboardScore userScore = (SwarmLeaderboardScore) object;
                return userScore;

        }
        public static void writesLeaderBoardToLocal(Context context, SwarmLeaderboardScore[] object){
                String path = context.getString(R.string.LocalLeaderBoardPath);
                LocalPersistence.witeObjectToFile(context, object, path);               

        }



        public synchronized static SwarmLeaderboardScore[]  readLeaderBoardFromLocal(Context context){
                String path = context.getString(R.string.LocalLeaderBoardPath);

                Object object = LocalPersistence.readObjectFromFile(context,path);




                SwarmLeaderboardScore[]  lb = (SwarmLeaderboardScore[]) object;
                return lb;

        }



        public static boolean isNetworkAvailable(Context context) {
                ConnectivityManager connectivityManager 
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                return activeNetworkInfo != null;
        }





        public static void addListener(HighScoreActivity listener){
                LeaderBoardInterface.listener = listener;
        }
        
        


}



